package lottery;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;

import code.lewdy.app.communication.Alert;
import code.lewdy.app.user.AccountRecord;
import code.lewdy.db.Database;
import code.lewdy.db.HibernateTemple;
import code.lewdy.db.JdbcUtil;
import code.lewdy.lottery.ExtUtil;
import code.lewdy.lottery.OpenRewardNumber;
import code.lewdy.lottery.UnionBuyRecord;
import code.lewdy.lottery.UnionBuySet;
import code.lewdy.util.FormatUtil;
import code.lewdy.util.RandomUtil;

import com.lt.member.Member;
import com.lt.member.MemberService;

import dao.HibernateSessionFactory;

/**
 * 实际盈亏 赢=中奖总金额-投注总金额+返点 亏=中奖总金额-投注总金额+返点 返点金额=投注总额*返点比例
 * 
 * @author liuding,2012-5-2 $LastChangedDate$ $Author$
 */
public class PayReward {

	private static final List<String> openList = null;
	JdbcUtil jdbc = new JdbcUtil(Database.TYPE_SQLSERVER);

	/**
	 * @param args
	 * @author liuding,2012-5-2
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PayReward p = new PayReward();
		int betId = 11; // 11~20
		BetRecord br = null;
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		br = (BetRecord) s.get(BetRecord.class, betId);
		s.getTransaction().commit();
		s.close();
		if (br == null) {
			System.out.println("BetRecord is NULL!");
			return;
		}
		p.doPay(br);
	}

	/**
	 * @param br
	 *            已存在数据库中的BetRecord
	 * @return
	 * @author liuding,2012-5-2
	 */
	public int doPay(BetRecord br) {
		if (br == null)
			return -1; // 数据为空
		if (br.getIsPay() != 0)
			return -2; // 已经派奖,不能重复派奖!
		if (br.getIsCancel() != 0)
			return -3; // 已经撤单，无效定单!
		Member m = (Member) HibernateTemple.load(Member.class, br.getOwnerId());
		int betCount = br.getCount(); // 总投
		int winCount = 0;
		float returnPoint = br.getReturnPoint();
		double payUnit = br.getPayUnit(); // 率
		double perPrice = br.getSingleAmount();// 单
		String number = br.getNumber();
		String openNumber = getOpenNumber(br);
		System.out.println("number:" + number);
		if (number == null || number.equals("")) {
			return -4; // 投注号码为空!
		}
		if (openNumber == null || openNumber.equals("")) {
			return -5; // 开奖号码为空!
		}
		String numArr[] = number.split("\\|"); // 分注
		for (String betNum : numArr) {
			winCount += getWinCount(br, betNum, openNumber);
		}

		if (br.getIsUnion() == 1) {
			// 如果是合买
			payUnionBuy(br, winCount);
			// payReturnTop(br); //下级消费返点给上级
			return 1;
		}
		// return
		double returnAmount = returnPoint * perPrice * betCount / 100;
		double winAmount = winCount * payUnit * perPrice;
		// double totalAmount = winAmount + returnAmount; // 总增量

		PayRewardRecord pr = new PayRewardRecord();
		pr.setAmount(winAmount);
		pr.setBetwayId(br.getBetId());
		pr.setBetwayName(br.getBetName());
		pr.setCreateDate(new Date());
		pr.setIsPay(1);
		pr.setIsWin(winAmount > 0 ? 1 : 0);
		pr.setLotteryId(br.getLotteryId());
		pr.setLotteryName(br.getLotteryName());
		pr.setWinCount(winCount);
		pr.setReturnPoint(br.getReturnPoint());
		pr.setReturnAmount(returnAmount);
		pr.setOrderId(br.getOrderId());

		HibernateTemple.save(pr);
		updateRewardAmount(br, winAmount, winCount); // 奖金派发
		payReturnAmount(br); // 派发返点
		payReturnTop(br); // 下级消费返点给上级
		if (winAmount > 0) {
			// 中奖后停止追号
			stopAfterBet(br);
		}
		return 1; // 派发成功
	}

	/**
	 * 处理合买订单
	 * 
	 * @param br
	 */
	private void payUnionBuy(BetRecord br, int winCount) {
		// TODO Auto-generated method stub
		UnionBuyRecord initiatorRr = null; // 发起人合买记录
		/*
		 * UnionBuySet set = (UnionBuySet) jdbc.getEntityBySQL(UnionBuySet.class
		 * .getName(), "select * from UnionBuySet where betId=" + br.getId());
		 */
		UnionBuySet set = (UnionBuySet) HibernateTemple
				.loadUnique("from UnionBuySet where betId=" + br.getId());
		// 合买发起人
		Member initiator = (Member) HibernateTemple.load(Member.class, Integer
				.parseInt("" + set.getInitiatorId()));
		double totalAmount = set.getPartPrice() * set.getPartCount(); // 投注订单总金额
		// double totalReturnAmount = br.getReturnPoint() * totalAmount / 100;
		// //总返点
		double totalBuyAmount = set.getTotalPaidAmount(); // 实际合买总金额
		double winAmount = winCount * br.getPayUnit() * br.getSingleAmount();
		double buyAmount = 0; // 一个合买记录中的实际买金额
		double factDivAmount = 0;// 实际分得的合买分成
		double factWin = 0;// 实际盈亏
		double factWinAmount = winAmount * totalBuyAmount / totalAmount; // 合买订单实际总奖金
		double royaltiesAmount = 0; // 发单人提成总额 ,从每个跟单人的奖金中按提成比例分取
		double tempRoyaltiesAmount = 0;
		double betRate = 0; // 个人投注比例
		double returnAmount = 0; // 个人返点
		double returnPoint = 0; // 各自数据库中账户返点比例
		// 是否为不定位投注?
		boolean isBDW = false;
		if (br.getBetName() != null && br.getBetName().contains("不定位")) {
			isBDW = true;
		}

		List<UnionBuyRecord> ubrs = (List<UnionBuyRecord>) HibernateTemple
				.list("from UnionBuyRecord where unionSetId=" + set.getId());
		for (UnionBuyRecord ubr : ubrs) {
			if (ubr.getOwnerId() == initiator.getId()) {
				// 发起人订单跳过，另外处理
				initiatorRr = ubr;
				continue;
			}
			Member m = (Member) HibernateTemple.load(Member.class, Integer
					.parseInt("" + ubr.getOwnerId()));

			returnPoint = isBDW ? m.getBdReturnPoint() : m.getReturnPoint();
			buyAmount = ubr.getPartPrice() * ubr.getBuyCount();
			betRate = buyAmount / totalBuyAmount;
			factDivAmount = factWinAmount * betRate; // 实际分成利润
			returnAmount = buyAmount * returnPoint / 100; // 分成返点
			factWin = factDivAmount - buyAmount; // 实际盈亏

			if (factWin > 0) {
				tempRoyaltiesAmount = factWin * set.getRoyaltiesRate() / 100;
				royaltiesAmount += tempRoyaltiesAmount;
				factDivAmount = factDivAmount - tempRoyaltiesAmount; // 减去发起人提成
				factWin = factWin - tempRoyaltiesAmount; // 实际盈亏减去提成
			}
			// 更新账户余额&账变记录
			MemberService.updateBalance(m, factDivAmount, ubr.getOrderId(),
					AccountRecord.GROUP_LOTTERY_UNION_PAY, "合买派奖");
			MemberService.updateBalance(m, returnAmount, ubr.getOrderId(),
					AccountRecord.GROUP_RETURN, "合买派奖返点");

			// 更新跟单记录
			ubr.setIsPay(1);
			ubr.setWinAmount(factDivAmount);
			HibernateTemple.update(ubr);

			// 添加提示信息
			factWin = FormatUtil.formatDecimal(factWin, 2);
			new Alert().save(m, "合买盈亏提示", "您的合买订单号" + br.getOrderId() + "\n彩种"
					+ br.getLotteryName() + "-期号" + br.getNumberId() + "-玩法"
					+ br.getBetName() + "\n实际赢亏" + factWin + "元,其中奖金"
					+ factDivAmount + "元\n扣除发起人提成" + tempRoyaltiesAmount
					+ "元\n跟单本金" + buyAmount + "元。");
			// 给上级返点
			payUnionReturnTop(ubr);
		}
		// =========================处理发起人订单==============================
		// 处理发起人订单
		returnPoint = isBDW ? initiator.getBdReturnPoint() : initiator
				.getReturnPoint();
		buyAmount = set.getInitiatorBuyCount() * set.getPartPrice();
		betRate = buyAmount / totalBuyAmount;
		factDivAmount = factWinAmount * betRate; // 实际分成利润
		returnAmount = buyAmount * returnPoint / 100; // 分成返点
		factWin = factDivAmount - buyAmount; // 实际盈亏
		// 账变记录
		MemberService.updateBalance(initiator, factDivAmount, br.getOrderId(),
				AccountRecord.GROUP_LOTTERY_UNION_PAY, "合买派奖");
		MemberService.updateBalance(initiator, returnAmount, br.getOrderId(),
				AccountRecord.GROUP_RETURN, "合买派奖返点");
		/*
		 * new AccountRecord().insert(initiator, br.getOrderId(),
		 * AccountRecord.GROUP_LOTTERY_UNION_PAY, factDivAmount, "合买派奖"); new
		 * AccountRecord().insert(initiator, br.getOrderId(),
		 * AccountRecord.GROUP_RETURN, returnAmount, "合买派奖返点");
		 */
		// 添加提示信息
		factWin = FormatUtil.formatDecimal(factWin, 2);
		new Alert().save(initiator, "合买盈亏提示", "您的合买订单号" + br.getOrderId()
				+ "\n彩种" + br.getLotteryName() + "-期号" + br.getNumberId()
				+ "-玩法" + br.getBetName() + "\n实际赢亏" + factWin + "元\n其中奖金"
				+ factDivAmount + "元\n跟单本金" + buyAmount + "元。");
		// 更新发起人跟单记录状态, 发起时的跟单，发起后不能跟自己的单
		if (initiatorRr != null) {
			initiatorRr.setIsPay(1);
			initiatorRr.setWinAmount(factDivAmount);
			HibernateTemple.update(initiatorRr);
			// 给上级返点
			payUnionReturnTop(initiatorRr);
		}

		// 更新订单状态
		br.setIsPay(1);
		br.setWinAmount(winAmount);
		br.setWinCount(winCount);
		HibernateTemple.update(br);

		// 派发跟单人提成
		royaltiesAmount = FormatUtil.formatDecimal(royaltiesAmount, 2);
		MemberService.updateBalance(initiator, royaltiesAmount,
				br.getOrderId(), AccountRecord.GROUP_LOTTERY_UNION_ROYALTY,
				"发起合买提成");
		/*
		 * initiator.setBalance(initiator.getBalance()+royaltiesAmount+factDivAmount
		 * +returnAmount); HibernateTemple.update(initiator); //更新账户余额
		 */
		// 消息提醒
		new Alert().save(initiator, "合买派奖提成消息", "您发起的合买订单" + br.getOrderId()
				+ "中奖派发，分得提成" + FormatUtil.formatDecimal(royaltiesAmount, 2)
				+ "元");
		// 更新派奖标识
		set.setIsPay(1);
		HibernateTemple.update(set);
	}

	/**
	 * 中奖后停止追号
	 * 
	 * @param br
	 */
	private void stopAfterBet(BetRecord br0) {
		// TODO Auto-generated method stub
		/*
		 * List<BetRecord> brs = (ArrayList<BetRecord>) jdbc .listAll(
		 * BetRecord.class.getName(), "where id<>" + br0.getId() +
		 * " and isChase=1 and isWinStop=1 and isPay=0 and isCancel=0 and" +
		 * " ownerId =" + br0.getOwnerId() + " and number='" + br0.getNumber() +
		 * "' and betBit='" + br0.getBetBit() + "' " + " and numberId<>'" +
		 * br0.getNumberId() + "'");
		 */
		String hql = "from BetRecord where  id<>"
				+ br0.getId()
				+ " and isChase=1 and isWinStop=1 and isPay=0 and isCancel=0 and"
				+ " ownerId =" + br0.getOwnerId() + " and number='"
				+ br0.getNumber() + "' and betBit='" + br0.getBetBit() + "' "
				+ " and numberId<>'" + br0.getNumberId() + "'";
		List<BetRecord> brs = (List<BetRecord>) HibernateTemple.list(hql);
		for (BetRecord br : brs) {
			br.setIsCancel(1); // 取消该订单
			HibernateTemple.update(br);

			double betAmount = br.getCount() * br.getSingleAmount();
			Member m = (Member) HibernateTemple.load(Member.class, br
					.getOwnerId());
			m.setBalance(betAmount + m.getBalance());

			AccountRecord ar = new AccountRecord();
			ar.setAmountIn(betAmount);
			ar.setBalance(m.getBalance());
			ar.setCreateDate(new Date());
			ar.setGroupId(AccountRecord.GROUP_AFTER_BET_CANCEL);
			ar.setNote("追号取消");
			ar.setOrderId(br.getOrderId());
			ar.setOwnerId(new Long(br.getOwnerId()));
			ar.setOwnerName(br.getOwnerName());
			ar.setType(AccountRecord.INCOME);
			/*
			 * MemberStatistics mts = (MemberStatistics)
			 * jdbc.getEntityBySQL(MemberStatistics.class.getName(),
			 * "select * from MemberStatistics where ownerId = "
			 * +br.getOwnerId());
			 * mts.setTotalBetAmount(mts.getTotalBetAmount()-betAmount);
			 * mts.setTotalWinAmount(mts.getTotalWinAmount()+betAmount);
			 * HibernateTemple.update(mts);
			 */
			HibernateTemple.update(m);
			HibernateTemple.save(ar);

		}
	}

	/**
	 * 下级合买消费返点给上级
	 * 
	 * @param br
	 */
	private void payUnionReturnTop(UnionBuyRecord ubr) {
		// TODO Auto-generated method stub
		double betAmount = ubr.getBuyCount();
		double amount = 0;
		int uid = Integer.parseInt("" + ubr.getOwnerId());
		Member m = (Member) HibernateTemple.load(Member.class, uid);
		List<Member> tops = MemberService.getTopMembers(m);
		if (tops == null) {
			return; // 无上级没有此业务处理
		}
		for (int i = 0; i < tops.size(); i++) {
			Member mt = tops.get(i);
			Member mttop = MemberService.getTopMember(mt);
			if (mttop != null) {
				// 更新账户余额
				amount = (mttop.getReturnPoint() - mt.getReturnPoint())
						* betAmount / 100;
				/*
				 * double addAmount = amount;
				 * JdbcTemple.executeUpdate("update Member set balance=balance+"
				 * +addAmount+" where id="+mttop.getId());
				 */
				MemberService.updateBalance(mttop, amount, ubr.getOrderId(),
						AccountRecord.GROUP_RETURN_LOWER, "下级"
								+ m.getUsername() + "投注返利");
				/*
				 * //账变记录 AccountRecord ar = new AccountRecord();
				 * ar.setAmountIn(amount);
				 * ar.setBalance(MemberService.getBalance(mttop.getId()));
				 * ar.setCreateDate(new Date());
				 * ar.setGroupId(AccountRecord.GROUP_RETURN_LOWER);
				 * ar.setNote("下级"+m.getUsername()+"投注");
				 * ar.setOrderId(ubr.getOrderId()); ar.setOwnerId(new
				 * Long(mttop.getId())); ar.setOwnerName(mttop.getUsername());
				 * ar.setType(AccountRecord.INCOME); HibernateTemple.save(ar);
				 */
			}
		}
		// 处理消费者直接上一级
		Member top = MemberService.getTopMember(m);
		if (top == null)
			return;

		amount = (top.getReturnPoint() - m.getReturnPoint()) * betAmount / 100;
		// 更新账户余额
		/*
		 * double addAmount = amount;
		 * JdbcTemple.executeUpdate("update Member set balance=balance+"
		 * +addAmount+" where id="+top.getId());
		 */
		MemberService.updateBalance(top, amount, ubr.getOrderId(),
				AccountRecord.GROUP_RETURN_LOWER, "下级" + m.getUsername()
						+ "投注返利");
	}

	/**
	 * 下级消费返点给上级
	 * 
	 * @param br
	 */
	private void payReturnTop(BetRecord br) {
		// TODO Auto-generated method stub
		double betAmount = br.getCount() * br.getSingleAmount();
		double amount = 0;
		int uid = br.getOwnerId();
		Member m = (Member) HibernateTemple.load(Member.class, uid);
		List<Member> tops = MemberService.getTopMembers(m);
		if (tops == null) {
			return; // 无上级没有此业务处理
		}
		for (int i = 0; i < tops.size(); i++) {
			Member mt = tops.get(i);
			Member mttop = MemberService.getTopMember(mt);
			if (mttop != null) {
				amount = (mttop.getReturnPoint() - mt.getReturnPoint())
						* betAmount / 100;
				// 更新账户余额
				double addAmount = amount;
				MemberService.updateBalance(mttop, addAmount, br.getOrderId(),
						AccountRecord.GROUP_RETURN_LOWER, "下级"
								+ m.getUsername() + "投注");
				/*
				 * JdbcTemple.executeUpdate("update Member set balance=balance+"
				 * + addAmount + " where id=" + mttop.getId()); // 账变记录
				 * AccountRecord ar = new AccountRecord();
				 * ar.setAmountIn(amount);
				 * ar.setBalance(MemberService.getBalance(mttop.getId()));
				 * ar.setCreateDate(new Date());
				 * ar.setGroupId(AccountRecord.GROUP_RETURN_LOWER);
				 * ar.setNote("下级" + m.getUsername() + "投注");
				 * ar.setOrderId(br.getOrderId()); ar.setOwnerId(new
				 * Long(mttop.getId())); ar.setOwnerName(mttop.getUsername());
				 * ar.setType(AccountRecord.INCOME);
				 * 
				 * HibernateTemple.save(ar);
				 */
			}
		}
		// 处理消费者直接上一级
		Member top = MemberService.getTopMember(m);
		if (top == null)
			return;
		amount = (top.getReturnPoint() - m.getReturnPoint()) * betAmount / 100;
		// top.setBalance(top.getBalance()+amount);
		// 更新账户余额
		double addAmount = amount;
		MemberService
				.updateBalance(top, addAmount, br.getOrderId(),
						AccountRecord.GROUP_RETURN_LOWER, "下级"
								+ m.getUsername() + "投注");
		/*
		 * JdbcTemple.executeUpdate("update Member set balance=balance+" +
		 * addAmount + " where id=" + top.getId()); // 账变记录 AccountRecord ar =
		 * new AccountRecord(); ar.setAmountIn(amount);
		 * ar.setBalance(MemberService.getBalance(top.getId()));
		 * ar.setCreateDate(new Date());
		 * ar.setGroupId(AccountRecord.GROUP_RETURN_LOWER); ar.setNote("下级" +
		 * m.getUsername() + "投注"); ar.setOrderId(br.getOrderId());
		 * ar.setOwnerId(new Long(top.getId()));
		 * ar.setOwnerName(top.getUsername()); ar.setType(AccountRecord.INCOME);
		 * HibernateTemple.save(ar);
		 */
	}

	/**
	 * 获得win注数
	 * 
	 * @param br
	 * @param betNumber
	 *            投注号码
	 * @param openNumber
	 * @return
	 */
	private int getWinCount(BetRecord br, String betNumber, String openNumber) {
		int winCount = 0;
		int totalCount = 0;
		// totalCount = getNumberCount(br, betNumber);
		winCount = isWin(br, betNumber, openNumber);
		return winCount;
	}

	/**
	 * 判断某一注号码的情况吧
	 *  判断某一注号码的情况吧
	 * 
	 * @param br
	 * @param betNumber
	 * @param openNumber
	 * @return 中奖注数
	 */
	public int isWin(BetRecord br, String betNumber, String openNumber) {
		int rewardCount = 0; // 奖金份数,中奖注数
		String bitSp = ",";
		String numTail = "@";
		int i = 0;
		int arrLength = 0;
		String lotteryName = br.getLotteryName();
		String betName = br.getBetName();
		String betFname = betName; // 可能为上一级
		if (openNumber.endsWith(bitSp))
			openNumber += numTail;
		if (betNumber.endsWith(bitSp))
			betNumber += numTail;
		String openNumArr[] = openNumber.split(bitSp);
		String betNumArr[] = betNumber.split(bitSp);
		String openValue = ""; // 开奖号码数据某个元素的值
		String bitArr[] = null;
		if (br.getBetBit() != null)
			bitArr = br.getBetBit().split(bitSp);
		boolean results = false;

		if (betName == null) {
			try {
				throw new Exception("派奖中betName为空!");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return 0;
		}

		if (betName.contains("复式") && !betName.contains("二星组选复式")) {
			results = false;
			int k = 0;
			arrLength = betNumArr.length > openNumArr.length ? betNumArr.length
					: openNumArr.length;
			for (i = 0; i < arrLength; i++) {
				betNumArr[i] = betNumArr[i].replace(numTail, "");
				if (betNumArr[i].length() > 0) {
					if (lotteryName.contains("3D")
							|| lotteryName.contains("P3")) {
						openValue = openNumArr[k]; // 3D开奖号码只有三个位置
					} else {
						openValue = openNumArr[i]; // 时时彩开奖号码要位位对应
					}
					if (betNumArr[i].contains(openValue)) {
						results = true;
					} else {
						results = false;
						return 0; // 有没包含在里面的即没有中奖！直接返回
					}
					k++;
				}
			}
			if (results)
				return 1;
			else
				return 0;
		} else if (betName.contains("组三") || betName.contains("组六")
				|| betName.contains("二星组选") || betName.contains("混合组选")
				|| betName.contains("单式")) {
			// 提取投注位置的开奖号码
			StringBuffer sb = new StringBuffer();
			String openBit = "";
			if (bitArr != null) {
				for (int j = 0; j < bitArr.length; j++) {
					if ("1".equals(bitArr[j])) {
						// 如果该位上有投注
						sb.append(openNumArr[j]);
					}
				}
				openBit = sb.toString();
				if (betName.contains("二星组选复式")) {
					if (openBit.charAt(0) == openBit.charAt(1)) {
						return 0; // 开奖号码为对子不中奖
					} else {
						if (betNumber.contains(openBit.charAt(0) + "")
								&& betNumber.contains(openBit.charAt(1) + "")) {
							return 1;
						}
					}
				} else if (betName.contains("单式") && !betName.contains("组选")) {
					if (betNumber.equals(openBit)) {
						return 1;
					} else {
						return 0;
					}
				} else if (betName.contains("混合组选")) {
					if (openBit.charAt(0) == openBit.charAt(1)
							&& openBit.charAt(1) == openBit.charAt(2)
							&& openBit.charAt(0) == openBit.charAt(2)) {
						// 开奖号码为豹子
						return 0;
					} 
					if (betNumber.contains(openBit.charAt(0) + "")
							&& betNumber.contains(openBit.charAt(1) + "")
							&& betNumber.contains(openBit.charAt(2) + "")) {
						String twiceValue = ExtUtil
								.getTwiceValueInThree(openBit);
						if (twiceValue != null) {
							// 如果开奖号码是组三
							String t2 = ExtUtil.getTwiceValueInThree(betNumber);
							if (twiceValue.equals(t2)) {
								return 1;
							} else {
								return 0;
							}
						} else {
							return 1;
						}
					} else {
						return 0;
					}
				} else {
					// 组六和组三
					if (openBit.charAt(0) != openBit.charAt(1)
							&& openBit.charAt(1) != openBit.charAt(2)
							&& openBit.charAt(0) != openBit.charAt(2)) {
						// 开奖号码为组六
						if (betName.contains("组三")) {
							return 0;
						} else if (betName.contains("组六")) {
							if (betNumber.contains(openBit.charAt(0) + "")
									&& betNumber.contains(openBit.charAt(1)
											+ "")
									&& betNumber.contains(openBit.charAt(2)
											+ "")) {
								return 1;
							} else {
								return 0;
							}
						}
					} else if (openBit.charAt(0) == openBit.charAt(1)
							&& openBit.charAt(1) == openBit.charAt(2)
							&& openBit.charAt(0) == openBit.charAt(2)) {
						// 开奖号码为豹子
						return 0;
					} else {
						// 开奖号码为组三
						if (betName.contains("组六")) {
							return 0;
						} else if (betName.contains("组三")) {
							if (betNumber.contains(openBit.charAt(0) + "")
									&& betNumber.contains(openBit.charAt(1)
											+ "")
									&& betNumber.contains(openBit.charAt(2)
											+ "")) {
								return 1;
							} else {
								return 0;
							}
						}
					}
				}
			}
		} else if (betName.contains("定位胆") || betName.contains("定位")
				&& !betName.contains("不")) {// ============定位胆
			// 投注号码对应包含开奖号码即中奖
			rewardCount = 0;
			int k = 0;
			for (int j = 0; j < betNumArr.length; j++) {
				if (lotteryName.contains("3D") || lotteryName.contains("P3")) {
					openValue = openNumArr[k]; // 3D开奖号码只有三个位置
				} else {
					openValue = openNumArr[j]; // 时时彩开奖号码要位位对应
				}
				if (j >= 2){
					k ++;
				}
				if(betNumArr[j].contains(openValue)) {
					rewardCount++;
				}
			}
			return rewardCount;
		} else if (betFname.contains("不定位")) {
			boolean is1m3D = false;
			boolean is2m3D = false;
			if (lotteryName.contains("3D") || lotteryName.contains("P3")) {
				if (betName.contains("1码不定位")) {
					is1m3D = true;
				} else if (betName.contains("2码不定位")) {
					is2m3D = true;
				}
			}
			// 三个位置全包含则为3份奖金
			if (betName.contains("前三1码") || is1m3D) {
				int containsCount = 0;
				if (!openNumArr[0].equals(openNumArr[1])
						&& !openNumArr[1].equals(openNumArr[2])
						&& !openNumArr[0].equals(openNumArr[2])) {
					// 开奖号码为组六号码(三个位置都不等)
					if (betNumber.contains(openNumArr[0]))
						containsCount++;
					if (betNumber.contains(openNumArr[1]))
						containsCount++;
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (containsCount == 1) {
						return 1;
					} else if (containsCount == 2) {
						return 2;
					} else if (containsCount == 3) {
						return 3;
					} else {
						return 0;
					}
				} else if (openNumArr[0].equals(openNumArr[1])
						&& openNumArr[1].equals(openNumArr[2])
						&& openNumArr[0].equals(openNumArr[2])) {
					// 开奖号码为豹子(三个位置都相等)
					if (betNumber.contains(openNumArr[0])
							|| betNumber.contains(openNumArr[1])
							|| betNumber.contains(openNumArr[2])) {
						return 1;
					} else {
						return 0;
					}
				} else {
					// 开奖号码为组三号码(两个位置相等)
					if (betNumber.contains(openNumArr[0]))
						containsCount++;
					if (betNumber.contains(openNumArr[1]))
						containsCount++;
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (containsCount == 3) {
						return 2;
					} else if(containsCount==1 || containsCount==2){
						return 1;
					}else{
						return 0;
					}
				}
			} else if (betName.contains("中三1码")) {// ======================中三1码不定位=================
				int containsCount = 0;
				if (!openNumArr[1].equals(openNumArr[2])
						&& !openNumArr[2].equals(openNumArr[3])
						&& !openNumArr[1].equals(openNumArr[3])) {
					// 开奖号码为组六号码(三个位置都不等)
					if (betNumber.contains(openNumArr[1]))
						containsCount++;
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (betNumber.contains(openNumArr[3]))
						containsCount++;
					if (containsCount == 1) {
						return 1;
					} else if (containsCount == 2) {
						return 2;
					} else if (containsCount == 3) {
						return 3;
					} else {
						return 0;
					}
				} else if (openNumArr[1].equals(openNumArr[2])
						&& openNumArr[2].equals(openNumArr[3])
						&& openNumArr[1].equals(openNumArr[3])) {
					// 开奖号码为豹子(三个位置都相等)
					if (betNumber.contains(openNumArr[1])
							|| betNumber.contains(openNumArr[2])
							|| betNumber.contains(openNumArr[3])) {
						return 1;
					} else {
						return 0;
					}
				} else {
					// 开奖号码为组三号码(两个位置相等)
					if (betNumber.contains(openNumArr[1]))
						containsCount++;
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (betNumber.contains(openNumArr[3]))
						containsCount++;
					if (containsCount == 3) {
						return 2;
					} else {
						return 0;
					}
				}
			} else if (betName.contains("后三1码")) {
				int containsCount = 0;
				if (!openNumArr[2].equals(openNumArr[3])
						&& !openNumArr[3].equals(openNumArr[4])
						&& !openNumArr[2].equals(openNumArr[4])) {
					// 开奖号码为组六号码(三个位置都不等)
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (betNumber.contains(openNumArr[3]))
						containsCount++;
					if (betNumber.contains(openNumArr[4]))
						containsCount++;
					if (containsCount == 1) {
						return 1;
					} else if (containsCount == 2) {
						return 2;
					} else if (containsCount == 3) {
						return 3;
					} else {
						return 0;
					}
				} else if (openNumArr[2].equals(openNumArr[3])
						&& openNumArr[3].equals(openNumArr[4])
						&& openNumArr[2].equals(openNumArr[4])) {
					// 开奖号码为豹子(三个位置都相等)
					if (betNumber.contains(openNumArr[2])
							|| betNumber.contains(openNumArr[3])
							|| betNumber.contains(openNumArr[4])) {
						return 1;
					} else {
						return 0;
					}
				} else {
					// 开奖号码为组三号码(两个位置相等)
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (betNumber.contains(openNumArr[3]))
						containsCount++;
					if (betNumber.contains(openNumArr[4]))
						containsCount++;
					if (containsCount == 3) {
						return 2;
					} else if (containsCount == 1 || containsCount == 2) {
						return 1;
					} else {
						return 0;
					}
				}
			} else if (betName.contains("前三2码") || is2m3D) {
				int containsCount = 0;
				if (!openNumArr[0].equals(openNumArr[1])
						&& !openNumArr[1].equals(openNumArr[2])
						&& !openNumArr[0].equals(openNumArr[2])) {
					// 开奖号码为组六号码(三个位置都不等)
					if (betNumber.contains(openNumArr[0]))
						containsCount++;
					if (betNumber.contains(openNumArr[1]))
						containsCount++;
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (containsCount == 2) {
						return 1;
					} else if (containsCount == 3) {
						return 3;
					} else {
						return 0;
					}
				} else if (openNumArr[0].equals(openNumArr[1])
						&& openNumArr[1].equals(openNumArr[2])
						&& openNumArr[0].equals(openNumArr[2])) {
					// 开奖号码为豹子(三个位置都相等)
					return 0;
				} else {
					// 开奖号码为组三号码(两个位置相等)
					if (betNumber.contains(openNumArr[0]))
						containsCount++;
					if (betNumber.contains(openNumArr[1]))
						containsCount++;
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (containsCount == 2 || containsCount == 3) {
						if(containsCount == 2){
							//如果这相等的两位是一样的，则return 0
							String openTemp = openNumArr[0]+openNumArr[1]+openNumArr[2];
							String twiceNumber = ExtUtil.getTwiceValueInThree(openTemp);
							openTemp = openTemp.replace(twiceNumber, "");
							if(!betNumber.contains(openTemp)){
								return 0;
							}
						}
						return 1;
					} else {
						return 0;
					}
				}
			} else if (betName.contains("中三2码")) {// =========================中三2码不定位
				int containsCount = 0;
				if (!openNumArr[1].equals(openNumArr[2])
						&& !openNumArr[2].equals(openNumArr[3])
						&& !openNumArr[1].equals(openNumArr[3])) {
					// 开奖号码为组六号码(三个位置都不等)
					if (betNumber.contains(openNumArr[1]))
						containsCount++;
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (betNumber.contains(openNumArr[3]))
						containsCount++;
					if (containsCount == 2) {
						return 1;
					} else if (containsCount == 3) {
						return 3;
					} else {
						return 0;
					}
				} else if (openNumArr[1].equals(openNumArr[2])
						&& openNumArr[2].equals(openNumArr[3])
						&& openNumArr[1].equals(openNumArr[3])) {
					// 开奖号码为豹子(三个位置都相等)
					return 0;
				} else {
					// 开奖号码为组三号码(两个位置相等)
					if (betNumber.contains(openNumArr[1]))
						containsCount++;
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (betNumber.contains(openNumArr[3]))
						containsCount++;
					if (containsCount == 2 || containsCount == 3) {
						if(containsCount == 2){
							//如果这相等的两位是一样的，则return 0
							String openTemp = openNumArr[1]+openNumArr[2]+openNumArr[3];
							String twiceNumber = ExtUtil.getTwiceValueInThree(openTemp);
							openTemp = openTemp.replace(twiceNumber, "");
							if(!betNumber.contains(openTemp)){
								return 0;
							}
						}
						return 1;
					} else {
						return 0;
					}
				}
			} else if (betName.contains("后三2码")) {
				int containsCount = 0;
				if (!openNumArr[2].equals(openNumArr[3])
						&& !openNumArr[3].equals(openNumArr[4])
						&& !openNumArr[2].equals(openNumArr[4])) {
					// 开奖号码为组六号码(三个位置都不等)
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (betNumber.contains(openNumArr[3]))
						containsCount++;
					if (betNumber.contains(openNumArr[4]))
						containsCount++;
					if (containsCount == 2) {
						return 1;
					} else if (containsCount == 3) {
						return 3;
					} else {
						return 0;
					}
				} else if (openNumArr[2].equals(openNumArr[3])
						&& openNumArr[3].equals(openNumArr[4])
						&& openNumArr[2].equals(openNumArr[4])) {
					// 开奖号码为豹子(三个位置都相等)
					return 0;
				} else {
					// 开奖号码为组三号码(两个位置相等)
					if (betNumber.contains(openNumArr[2]))
						containsCount++;
					if (betNumber.contains(openNumArr[3]))
						containsCount++;
					if (betNumber.contains(openNumArr[4]))
						containsCount++;
					if (containsCount == 2 || containsCount == 3) {
						if(containsCount == 2){
							//如果这相等的两位是一样的，则return 0
							String openTemp = openNumArr[2]+openNumArr[3]+openNumArr[4];
							String twiceNumber = ExtUtil.getTwiceValueInThree(openTemp);
							openTemp = openTemp.replace(twiceNumber, "");
							if(!betNumber.contains(openTemp)){
								return 0;
							}
						}
						return 1;
					} else {
						return 0;
					}
				}
			}
		} else {
			System.out.println("开奖未处理的方式：" + betFname + ":" + betName);
		}
		return 0;
	}

	/**
	 * 计算某个投注号码的注数,因对于一个投注号码来说，中奖注数只算一注，此方法固定返回1
	 * 
	 * @param betName
	 *            投注类型
	 * @param betNumber
	 *            投注号码
	 * @return
	 */
	public int getNumberCount(BetRecord br, String betNumber) {
		return 1;
		/*
		 * int count = 0;
		 * System.out.println("PayReward.getNumberCount()=>投注号码:"+betNumber);
		 * String sp = ","; String numArr[] = null; //betNumber.split(sp);
		 * String lotteryName = br.getLotteryName()!=null ? br.getLotteryName()
		 * : ""; String betName = br.getBetName()!=null ? br.getBetName() : "";
		 * if(lotteryName.indexOf("时时彩")>=0){ if(betName.indexOf("复式")>=0){
		 * numArr = betNumber.split(sp); count = 1; for(String num : numArr){
		 * if(num != null && num.length()>0){ count *= num.length(); } } }else
		 * if(betName.indexOf("二星组选单式")>=0){ count =
		 * betNumber.length()*(betNumber.length()-1); }else
		 * if(betName.indexOf("组三")>=0){ count =
		 * 3*betNumber.length()*(betNumber.length()-1); }else
		 * if(betName.indexOf("组六")>=0){ count =
		 * betNumber.length()*(betNumber.length()-1)*(betNumber.length()-2);
		 * }else if(betName.indexOf("混合组选")>=0){ if(betNumber.length()==3){
		 * if(betNumber.charAt(0) != betNumber.charAt(1) && betNumber.charAt(1)
		 * != betNumber.charAt(2) && betNumber.charAt(0) != betNumber.charAt(2)
		 * ){ count = 6; //组六号码 }else{ count = 3; //组三号码 } }else{
		 * System.out.println("PayReward.getNumberCount()=>混合组选投注号码位数不是3位！"); }
		 * }else if(betName.indexOf("单式")>=0 && betName.indexOf("组选")<0){ count
		 * = 1; }else if(betName.indexOf("定位胆")>=0 ||
		 * betName.indexOf("1码不定位")>=0 || betName.indexOf("一码不定位")>=0){ numArr =
		 * betNumber.split(sp); count = 0; for(String num : numArr){ if(num !=
		 * null && num.length()>0){ count += num.length(); } } }else
		 * if(betName.indexOf("2码不定位")>=0 || betName.indexOf("二码不定位")>=0){ count
		 * = betNumber.length()*(betNumber.length()-1)/2; }else{
		 * System.out.println("PayReward.getNumberCount()=>未处理的投注方法:"+betName);
		 * } }else{
		 * System.out.println("PayReward.getNumberCount()=>未处理的彩种:"+lotteryName
		 * ); } return count;
		 */
	}

	public String getOpenNumber(BetRecord br) {
		String openNumber = "";
		if (br == null)
			return null;
		int lotteryId = br.getLotteryId();
		String numberId = br.getNumberId();
		/*
		 * OpenRewardNumber openObj = (OpenRewardNumber) jdbc.getEntityBySQL(
		 * OpenRewardNumber.class.getName(),
		 * "select * from OpenRewardNumber where lotteryId=" + lotteryId +
		 * " and periodNo='" + numberId + "'");
		 */
		String hql = "from OpenRewardNumber where  lotteryId=" + lotteryId
				+ " and periodNo='" + numberId + "' ";
		OpenRewardNumber openObj = (OpenRewardNumber) HibernateTemple
				.loadUnique(hql);
		if (openObj == null)
			return null;
		openNumber = openObj.getNumber();
		System.out.println("openNumber:" + openNumber);
		return openNumber;
	}

	/**
	 * 更新账户奖金,投注订单状态
	 * 
	 * @param br
	 * @param winAmount
	 * @return
	 */
	public int updateRewardAmount(BetRecord br, double winAmount, int winCount) {
		Member m = (Member) HibernateTemple.load(Member.class, br.getOwnerId());
		if (m == null) {
			System.out.println("updateRewardAmount()=>Member is NULL!");
			return -1;
		}
		BetRecord br2 = (BetRecord) HibernateTemple.load(BetRecord.class, br
				.getId());
		br2.setIsPay(1);
		br2.setWinAmount(winAmount);
		br2.setWinCount(winCount);

		m.setBalance(m.getBalance() + winAmount);
		AccountRecord ar = new AccountRecord();
		ar.setAmountIn(winAmount);
		ar.setBalance(m.getBalance());
		ar.setCreateDate(new Date());
		ar.setGroupId(AccountRecord.GROUP_REWARD_PAY);
		ar.setNote("中奖派发");
		ar.setOrderId(RandomUtil.getRandomString(18));
		ar.setOwnerId(new Long(m.getId()));
		ar.setOwnerName(m.getUsername());
		ar.setType(AccountRecord.INCOME);
		/*
		 * MemberStatistics mss = (MemberStatistics) HibernateTemple
		 * .loadUnique("from MemberStatistics where ownerId="+ar.getOwnerId());
		 * if(mss != null){
		 * mss.setTotalRewardAmout(mss.getTotalRewardAmout()+winAmount);
		 * mss.setTotalWinAmount(mss.getTotalWinAmount()+winAmount);
		 * HibernateTemple.update(mss); }else{System.out.println(
		 * "PayReward.updateRewardAmount=>MemberStatistics is NULL!"); }
		 */
		HibernateTemple.update(m);
		HibernateTemple.save(ar);
		HibernateTemple.update(br2); // 更新投注订单
		// 添加提示信息
		double factWin = winAmount - br.getSingleAmount() * br.getCount();
		new Alert().save(m, "投注订单盈亏提示", "您的投注\n单号-" + br.getOrderId() + "\n彩种-"
				+ br.getLotteryName() + "\n期号-" + br.getNumberId() + "\n玩法-"
				+ br.getBetName() + "\n实际赢亏		" + factWin + "元");
		return 1;
	}

	/**
	 * 派发返点
	 * 
	 * @return
	 */
	public int payReturnAmount(BetRecord br) {
		Member m = (Member) HibernateTemple.load(Member.class, br.getOwnerId());
		if (m == null) {
			System.out.println("payReturnAmount()=>Member is NULL!");
			return -1;
		}
		double amount = br.getSingleAmount() * br.getCount()
				* br.getReturnPoint() / 100; // 返点除以100
		m.setBalance(m.getBalance() + amount);
		AccountRecord ar = new AccountRecord();
		ar.setAmountIn(amount);
		ar.setBalance(m.getBalance());
		ar.setCreateDate(new Date());
		ar.setGroupId(AccountRecord.GROUP_RETURN);
		ar.setNote("返点派发");
		ar.setOrderId(RandomUtil.getRandomString(18));
		ar.setOwnerId(new Long(m.getId()));
		ar.setOwnerName(m.getUsername());
		ar.setType(AccountRecord.INCOME);
		/*
		 * MemberStatistics mss = (MemberStatistics) HibernateTemple
		 * .loadUnique("from MemberStatistics where ownerId="+ar.getOwnerId());
		 * mss.setTotalReturnAmount(mss.getTotalReturnAmount() + amount);
		 * mss.setTotalWinAmount(mss.getTotalWinAmount()+amount);
		 * HibernateTemple.update(mss);
		 */
		HibernateTemple.update(m);
		HibernateTemple.save(ar);
		return 1;
	}

	/**
	 * 按开奖号码自动派奖
	 * 
	 * @param num
	 *            开奖号码
	 */
	public void payReward(OpenRewardNumber num) {
		/*
		 * List<BetRecord> brs = (List<BetRecord>) jdbc
		 * .list("lottery.BetRecord", "where isPay=0 and lotteryId=" +
		 * num.getLotteryId() + " and numberId='" + num.getPeriodNo() + "'", 1,
		 * 10000);
		 */
		String hql = "from BetRecord where isPay=0 and lotteryId="
				+ num.getLotteryId() + " and numberId='" + num.getPeriodNo()
				+ "' ";
		List<BetRecord> brs = (List<BetRecord>) HibernateTemple.list(hql);
		for (BetRecord br : brs) {
			if (br == null) {
				return;
			}
			int results = doPay(br);
		}
	}
}
